import { userLogin, getUserInfo } from '../../api/user.js'
import global from '../../utils/global.js'
import Cookie from "js-cookie";

const user = {
  state: {
    token: null,
    userId: null,
    userInfo: {},
    schoolId: null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_SCHOOL_ID: (state, schoolId) => {
      state.schoolId = schoolId
    },
    SET_SCHOOL_NAME: (state, schoolName) => {
      state.schoolName = schoolName
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.userName;
      const password = userInfo.password;
      return new Promise((resolve, reject) => {
        userLogin({
          "userName": username,
          "passWord": password,
          "platForm": 1
        }).then(response => {
          const data = response.data.data;
          commit('SET_TOKEN', data.token);
          commit('SET_USER_ID', data.schoolId);
          Cookie.set(global.tokenTag, data.token);
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          const data = response.data.data;
          // console.log(data);
          commit('SET_USER_INFO', data);
          commit('SET_SCHOOL_ID', data.schoolId);
          commit('SET_SCHOOL_NAME', data.schoolName);
          Cookie.set(global.userInfoTag, JSON.stringify(data));
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
};

export default user
